@model List<MVCWeekOne.Models.RouteDto>
@{
    ViewData["Title"] = "工艺路线管理";
}

<!-- Bootstrap CSS -->
<link href="~/lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- FontAwesome图标（使用CDN，避免本地404） -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />

<div class="route-management">
    <!-- 工艺路线列表 -->
    <div class="management-card">
        <div class="card-header">
            <h2>
                <span class="icon">⚙️</span>
                工艺路线管理
            </h2>
            <div>
                <button class="btn btn-success" onclick="addNewRoute()">
                    <i class="fas fa-plus"></i> 新增路线
                </button>
                <button class="btn btn-info" onclick="exportRoutes()">
                    <i class="fas fa-download"></i> 导出
                </button>
                <button class="btn btn-warning" onclick="importRoutes()">
                    <i class="fas fa-upload"></i> 导入
                </button>
                <button class="btn btn-secondary" onclick="location.reload()" title="刷新页面">
                    <i class="fas fa-redo"></i> 刷新
                </button>
                <button class="btn btn-danger" onclick="deleteSelectedRoute()" id="deleteBtn" disabled>
                    <i class="fas fa-trash"></i> 删除
                </button>
            </div>
        </div>

        <div class="toolbar">
            <div class="search-box">
                <form method="get" asp-action="Index"
                    style="display: flex; gap: 15px; align-items: center; flex-wrap: wrap;">
                    <input type="text" name="routeCode" value="@ViewBag.RouteCode" placeholder="工艺路线编号"
                        class="search-input">
                    <input type="text" name="routeName" value="@ViewBag.RouteName" placeholder="工艺路线名称"
                        class="search-input">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search"></i> 查询
                    </button>
                    <button type="button" class="btn" onclick="clearSearch()" style="background: #f7f7f7; color: #666;">
                        <i class="fas fa-redo"></i> 重置
                    </button>
                </form>
            </div>
        </div>

        @if (!string.IsNullOrEmpty(ViewBag.ErrorMessage?.ToString()))
        {
            <div class="alert alert-danger" role="alert">
                <i class="fas fa-exclamation-circle"></i>
                @ViewBag.ErrorMessage
            </div>
        }

        <div style="overflow-x: auto;">
            <table class="data-table" id="routeTable">
                <thead>
                    <tr>
                        <th style="width: 60px;">序号</th>
                        <th>工艺路线编号</th>
                        <th>工艺路线名称</th>
                        <th style="width: 80px;">状态</th>
                        <th style="width: 150px;">创建时间</th>
                        <th style="width: 100px;">创建人</th>
                        <th style="width: 100px;">修改人</th>
                        <th style="width: 150px;">修改时间</th>
                        <th style="width: 120px;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    @if (Model != null && Model.Any())
                    {
                        @for (int i = 0; i < Model.Count; i++)
                        {
                            var route = Model[i];
                            var rowIndex = ((ViewBag.CurrentPage - 1) * ViewBag.PageSize) + i + 1;
                            <tr onclick="selectRoute(@route.RouteId, this)" data-route-id="@route.RouteId">
                                <td>@rowIndex</td>
                                <td><a href="javascript:void(0)" onclick="openRouteModal(@route.RouteId)"
                                        style="font-weight:600; color: #007bff;">@route.RouteCode</a></td>
                                <td>
                                    <span style="color: #007bff; cursor: pointer; font-weight: 500;"
                                        onclick="event.stopPropagation(); editRouteAndProcesses(@route.RouteId, '@route.RouteCode', '@route.RouteName', @route.IsEnabled.ToString().ToLower())">
                                        @route.RouteName
                                    </span>
                                </td>
                                <td>
                                    @if (route.IsEnabled)
                                    {
                                        <span class="status-badge status-active">启用</span>
                                    }
                                    else
                                    {
                                        <span class="status-badge" style="background: #f56c6c; color: white;">禁用</span>
                                    }
                                </td>
                                <td>@route.CreateTime.ToString("yyyy-MM-dd HH:mm")</td>
                                <td>@(route.CreateUser ?? "-")</td>
                                <td>@(route.UpdateUser ?? "-")</td>
                                <td>@(route.UpdateTime?.ToString("yyyy-MM-dd HH:mm") ?? "-")</td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary"
                                        onclick="event.stopPropagation(); editRouteAndProcesses(@route.RouteId, '@route.RouteCode', '@route.RouteName', @route.IsEnabled.ToString().ToLower())"
                                        title="编辑">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger"
                                        onclick="event.stopPropagation(); deleteRoute(@route.RouteId, '@route.RouteName')"
                                        title="删除">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        }
                    }
                    else
                    {
                        <tr>
                            <td colspan="9" class="empty-state">
                                <i class="fas fa-inbox"></i>
                                <div>暂无工艺路线数据</div>
                                <div style="color: #999; font-size: 14px; margin-top: 5px;">点击"新增路线"按钮添加您的第一条工艺路线</div>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>

        <!-- 分页 -->
        @if (ViewBag.TotalCount > 0)
        {
            <div style="margin-top: 20px; text-align: center;">
                <div id="pagination"></div>
            </div>
        }
    </div>

    <!-- 工序明细 -->
    <div class="management-card details-section" id="processListSection" style="display: none;">
        <div class="details-header">
            <span>🔧 工序列表</span>
            <span id="selectedRouteInfo" style="margin-left: 20px; font-weight: normal; color: #666;"></span>
            <button type="button" class="btn btn-sm btn-secondary" onclick="hideProcessList()"
                style="float: right; margin-top: -5px;">
                <i class="fas fa-times"></i> 收起
            </button>
        </div>

        <div id="processContent">
            <div class="loading" id="processLoading">
                <i class="fas fa-spinner"></i>
                <div style="margin-top: 10px;">正在加载工序数据...</div>
            </div>
        </div>
    </div>
</div>

@section Styles {
    <style>
        .route-management {
            padding: 20px;
            background: #f5f7fa;
            min-height: 100vh;
        }

        .management-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            overflow: hidden;
        }

        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .card-header h2 {
            margin: 0;
            font-size: 20px;
            font-weight: 600;
            display: flex;
            align-items: center;
        }

        .card-header .icon {
            font-size: 24px;
            margin-right: 10px;
        }

        .toolbar {
            padding: 20px;
            border-bottom: 1px solid #e8eaec;
            background: #fafbfc;
        }

        .search-box {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .search-input {
            padding: 8px 15px;
            border: 1px solid #dcdee2;
            border-radius: 4px;
            font-size: 14px;
            min-width: 200px;
        }

        .btn {
            padding: 8px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #5cadff;
            color: white;
        }

        .btn-success {
            background: #19be6b;
            color: white;
        }

        .btn-info {
            background: #17a2b8;
            color: white;
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-outline-primary {
            border: 1px solid #007bff;
            color: #007bff;
            background: transparent;
        }

        .btn-outline-danger {
            border: 1px solid #dc3545;
            color: #dc3545;
            background: transparent;
        }

        .btn:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .btn-sm {
            padding: 4px 8px;
            font-size: 12px;
            border-radius: 3px;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }

        .data-table thead {
            background: #f8f8f9;
        }

        .data-table th,
        .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e8eaec;
            font-size: 14px;
        }

        .data-table th {
            color: #515a6e;
            font-weight: 600;
            white-space: nowrap;
        }

        .data-table tbody tr {
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .data-table tbody tr:hover {
            background: #f0f9ff;
        }

        .data-table tbody tr.selected {
            background: #e8f4fd;
            border-left: 3px solid #2d8cf0;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-active {
            background: #e1f5fe;
            color: #01579b;
        }

        .details-section {
            padding: 0;
            display: none;
        }

        .details-header {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #e8eaec;
            font-weight: 600;
            color: #495057;
            position: relative;
        }

        .loading {
            text-align: center;
            padding: 40px 20px;
            color: #8c8c8c;
        }

        .loading i {
            font-size: 24px;
            animation: spin 1s linear infinite;
        }

        @@keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #8c8c8c;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            color: #d9d9d9;
        }

        input[type="checkbox"] {
            transform: scale(1.2);
            margin: 0;
            cursor: pointer;
        }

        .card-header .btn {
            margin-left: 10px;
        }

        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid transparent;
            border-radius: 4px;
        }

        .alert-danger {
            color: #721c24;
            background-color: #f8d7da;
            border-color: #f5c6cb;
        }

        #pagination {
            text-align: center;
            padding: 20px 0;
        }

        /* 简洁样式结束 */
    </style>
}

@section Scripts {
    <script>
        layui.use(['laypage', 'layer'], function () {
            var laypage = layui.laypage;
            var layer = layui.layer;

            // 分页
            @if (ViewBag.TotalCount > 0)
                {
                    <text>
                        laypage.render({
                            elem: 'pagination',
                        count: @ViewBag.TotalCount,
                        limit: @ViewBag.PageSize,
                        curr: @ViewBag.CurrentPage,
                        layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                        jump: function(obj, first) {
                                                                if (!first) {
                                                                    var url = new URL(window.location);
                        url.searchParams.set('page', obj.curr);
                        url.searchParams.set('size', obj.limit);
                        window.location.href = url.toString();
                                                                }
                                                            }
                                                        });
                    </text>
            }
                            });

        // 当前选中的工艺路线ID
        let selectedRouteId = null;

        // 选择工艺路线（点击行）
        function selectRoute(routeId, element) {
            // 移除所有行的选中状态
            const allRows = document.querySelectorAll('#routeTable tbody tr');
            allRows.forEach(row => row.classList.remove('selected'));

            // 选中当前行
            element.classList.add('selected');
            selectedRouteId = routeId;

            // 显示工序详情
            showRouteDetails(routeId, element);

            // 更新删除按钮状态
            updateDeleteButton();
        }

        // 显示工艺路线详情
        function showRouteDetails(routeId, row) {
            const routeName = row.children[2].textContent;
            document.getElementById('selectedRouteInfo').textContent = `工艺路线: ${routeName}`;
            loadProcessList(routeId);
        }

        // 更新删除按钮状态
        function updateDeleteButton() {
            const deleteBtn = document.getElementById('deleteBtn');
            deleteBtn.disabled = selectedRouteId === null;
        }

        // 加载工序列表
        function loadProcessList(routeId) {
            document.getElementById('processListSection').style.display = 'block';

            const processContent = document.getElementById('processContent');
            processContent.innerHTML = `
                                    <div class="loading">
                                        <i class="fas fa-spinner"></i>
                                        <div style="margin-top: 10px;">正在加载工序数据...</div>
                                    </div>`;

            // 滚动到工序列表区域
            document.getElementById('processListSection').scrollIntoView({ behavior: 'smooth' });

            // 调用API获取工序数据
            const apiUrl = `@ViewBag.ReadApiUrl/Route/${routeId}/steps`;
            console.log('调用API获取工序数据，URL:', apiUrl);

            fetch(apiUrl)
                .then(response => {
                    console.log('API响应状态:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('API返回数据:', data);
                    console.log('数据检查 - code:', data.code, 'data:', data.data, 'data.length:', data.data ? data.data.length : 'null');

                    if (data.code === 200 && data.data && data.data.length > 0) {
                        // 有数据时显示表格
                        let tableRows = '';
                        data.data.forEach((step, index) => {
                            const createTime = step.createTime ? new Date(step.createTime).toLocaleString('zh-CN', {
                                year: 'numeric',
                                month: '2-digit',
                                day: '2-digit',
                                hour: '2-digit',
                                minute: '2-digit'
                            }) : '-';

                            tableRows += `
                                                     <tr>
                                                         <td><input type="checkbox" class="step-checkbox" value="${step.id}"></td>
                                                         <td>${index + 1}</td>
                                                         <td>${step.processCode || '-'}</td>
                                                         <td>${step.processName || '-'}</td>
                                                         <td>${step.reportingPermissions || '-'}</td>
                                                         <td>${index + 1}</td>
                                                         <td>${step.ratio ? step.ratio.toFixed(2) : '-'}</td>
                                                         <td>${createTime}</td>
                                                         <td>-</td>
                                                         <td>
                                                             <button class="btn btn-sm btn-outline-primary" onclick="editProcess(${step.id})" title="编辑">
                                                                 <i class="fas fa-edit"></i>
                                                             </button>
                                                         </td>
                                                     </tr>`;
                        });

                        processContent.innerHTML = `
                                                <div style="margin-bottom: 15px;">
                                                    <button class="btn btn-danger" id="batchDeleteBtn" onclick="batchDeleteSteps()" disabled>
                                                        <i class="fas fa-trash"></i> 批量删除工序
                                                    </button>
                                                </div>
                                                <div style="overflow-x: auto;">
                                                    <table class="data-table">
                                                        <thead>
                                                            <tr>
                                                                <th style="width: 40px;"><input type="checkbox" id="selectAllSteps" onchange="toggleAllSteps(this)"></th>
                                                                <th style="width: 60px;">序号</th>
                                                                <th>工序编号</th>
                                                                <th>工序名称</th>
                                                                <th style="width: 120px;">报工权限</th>
                                                                <th style="width: 80px;">顺序号</th>
                                                                <th style="width: 100px;">报工配比</th>
                                                                <th style="width: 150px;">创建时间</th>
                                                                <th style="width: 100px;">创建人</th>
                                                                <th style="width: 80px;">操作</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            ${tableRows}
                                                        </tbody>
                                                    </table>
                                                </div>`;

                        // 添加复选框变化事件监听
                        setTimeout(() => {
                            document.querySelectorAll('.step-checkbox').forEach(checkbox => {
                                checkbox.addEventListener('change', updateBatchDeleteButton);
                            });
                        }, 100);
                    } else {
                        // 无数据时显示空状态
                        processContent.innerHTML = `
                                                <div style="margin-bottom: 15px;">
                                                    <button class="btn btn-danger" id="batchDeleteBtn" onclick="batchDeleteSteps()" disabled>
                                                        <i class="fas fa-trash"></i> 批量删除工序
                                                    </button>
                                                </div>
                                                <div style="overflow-x: auto;">
                                                    <table class="data-table">
                                                        <thead>
                                                            <tr>
                                                                <th style="width: 40px;"><input type="checkbox" id="selectAllSteps" onchange="toggleAllSteps(this)" disabled></th>
                                                                <th style="width: 60px;">序号</th>
                                                                <th>工序编号</th>
                                                                <th>工序名称</th>
                                                                <th style="width: 120px;">报工权限</th>
                                                                <th style="width: 80px;">顺序号</th>
                                                                <th style="width: 100px;">报工配比</th>
                                                                <th style="width: 150px;">创建时间</th>
                                                                <th style="width: 100px;">创建人</th>
                                                                <th style="width: 80px;">操作</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr>
                                                                <td colspan="10" class="empty-state">
                                                                    <i class="fas fa-box-open"></i>
                                                                    <div>该工艺路线暂无工序数据</div>
                                                                </td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div>`;
                    }
                })
                .catch(error => {
                    console.error('加载工序列表失败:', error);
                    processContent.innerHTML = `
                                            <div style="text-align: center; padding: 40px; color: #f56c6c;">
                                                <i class="fas fa-exclamation-triangle" style="font-size: 24px; margin-bottom: 10px;"></i>
                                                <div>加载工序数据失败</div>
                                                <div style="font-size: 14px; margin-top: 5px;">${error.message}</div>
                                            </div>`;
                });
        }

        // 隐藏工序列表
        function hideProcessList() {
            document.getElementById('processListSection').style.display = 'none';
        }

        // 清空搜索条件
        function clearSearch() {
            window.location.href = '@Url.Action("Index", "Route")';
        }

        // 打开工艺路线详情模态框
        function openRouteModal(routeId) {
            // 这里可以添加打开详情模态框的逻辑
            console.log('打开工艺路线详情:', routeId);
        }

        // 删除选中的工艺路线
        function deleteSelectedRoute() {
            if (selectedRouteId === null) {
                alert('请先选择要删除的工艺路线');
                return;
            }

            const selectedRow = document.querySelector(`tr[data-route-id="${selectedRouteId}"]`);
            if (selectedRow) {
                const routeName = selectedRow.children[2].textContent;
                if (confirm(`确定要删除工艺路线 "${routeName}" 吗？`)) {
                    deleteRoute(selectedRouteId, routeName);
                }
            }
        }

        // 编辑工序
        function editProcess(processId) {
            console.log('编辑工序:', processId);
            // 这里可以添加编辑工序的逻辑
        }



        // 全选/取消全选工序
        function toggleAllSteps(selectAllCheckbox) {
            const stepCheckboxes = document.querySelectorAll('.step-checkbox');
            stepCheckboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
            });
            updateBatchDeleteButton();
        }

        // 更新批量删除按钮状态
        function updateBatchDeleteButton() {
            const checkedBoxes = document.querySelectorAll('.step-checkbox:checked');
            const batchDeleteBtn = document.getElementById('batchDeleteBtn');
            const selectAllCheckbox = document.getElementById('selectAllSteps');

            if (batchDeleteBtn) {
                batchDeleteBtn.disabled = checkedBoxes.length === 0;
            }

            // 更新全选复选框状态
            if (selectAllCheckbox) {
                const totalCheckboxes = document.querySelectorAll('.step-checkbox');
                if (totalCheckboxes.length > 0) {
                    selectAllCheckbox.checked = checkedBoxes.length === totalCheckboxes.length;
                    selectAllCheckbox.indeterminate = checkedBoxes.length > 0 && checkedBoxes.length < totalCheckboxes.length;
                }
            }
        }

        // 批量删除工序
        function batchDeleteSteps() {
            const checkedBoxes = document.querySelectorAll('.step-checkbox:checked');
            if (checkedBoxes.length === 0) {
                layer.msg('请先选择要删除的工序', { icon: 2 });
                return;
            }

            const stepIds = Array.from(checkedBoxes).map(checkbox => parseInt(checkbox.value));

            layer.confirm(`确定要删除选中的 ${stepIds.length} 个工序吗？删除后将无法恢复！`, {
                icon: 3,
                title: '确认批量删除'
            }, function (index) {
                // 调用批量删除API
                fetch(`@ViewBag.WriteApiUrl/Route/delete-steps`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        stepIds: stepIds,
                        operateBy: 'current_user' // 这里应该替换为当前登录用户
                    })
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 200) {
                            layer.msg('删除成功', { icon: 1 });
                            // 重新加载工序数据
                            if (selectedRouteId) {
                                loadProcessList(selectedRouteId);
                            }
                        } else {
                            layer.msg(data.msg || '删除失败', { icon: 2 });
                        }
                    })
                    .catch(error => {
                        console.error('批量删除失败:', error);
                        layer.msg('删除失败，请稍后重试', { icon: 2 });
                    });

                layer.close(index);
            });
        }

        // 页面加载完成后的初始化
        $(document).ready(function () {
            // 如果有数据，默认选中第一行
            const firstRow = document.querySelector('#routeTable tbody tr:first-child');
            if (firstRow && firstRow.dataset.routeId) {
                selectRoute(parseInt(firstRow.dataset.routeId), firstRow);
            }
        });

        // 新增工艺路线
        function addNewRoute() {
            layer.open({
                type: 1,
                title: '新增工艺路线',
                shadeClose: false,
                shade: 0.3,
                maxmin: true,
                area: ['900px', '600px'],
                content: getRouteFormHtml(),
                success: function (layero, index) {
                    // 初始化表单
                    initRouteForm('add', null, index);
                }
            });
        }

        // 编辑工艺路线和工序
        function editRouteAndProcesses(routeId, routeCode, routeName, isEnabled) {
            // 先获取工艺路线详情
            const loadIndex = layer.load(1, {
                shade: [0.3, '#fff']
            });

            fetch(`@ViewBag.ReadApiUrl/Route/${routeId}`)
                .then(response => response.json())
                .then(data => {
                    layer.close(loadIndex);

                    if (data.code === 200 && data.data) {
                        layer.open({
                            type: 1,
                            title: `编辑工艺路线 - ${routeName}`,
                            shadeClose: false,
                            shade: 0.3,
                            maxmin: true,
                            area: ['900px', '600px'],
                            content: getRouteFormHtml(),
                            success: function (layero, index) {
                                // 初始化编辑表单
                                initRouteForm('edit', data.data, index);
                            }
                        });
                    } else {
                        layer.msg('获取工艺路线信息失败', { icon: 2 });
                    }
                })
                .catch(error => {
                    layer.close(loadIndex);
                    console.error('获取工艺路线详情失败:', error);
                    layer.msg('获取工艺路线信息失败', { icon: 2 });
                });
        }

        // 删除工艺路线
        function deleteRoute(routeId, routeName) {
            // 首先检查是否有工序数据
            fetch(`@ViewBag.ReadApiUrl/Route/${routeId}/steps`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200 && data.data && data.data.length > 0) {
                        layer.msg('该工艺路线下还有工序数据，请先删除工序后再删除工艺路线', { icon: 2 });
                        return;
                    }

                    // 没有工序数据，可以删除工艺路线
                    layer.confirm(`确定要删除工艺路线 "${routeName}" 吗？删除后将无法恢复！`, {
                        icon: 3,
                        title: '确认删除'
                    }, function (index) {
                        // 调用删除API
                        fetch(`@ViewBag.WriteApiUrl/Route/delete`, {
                            method: 'DELETE',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                id: routeId,
                                operateBy: 'current_user' // 这里应该替换为当前登录用户
                            })
                        })
                            .then(response => response.json())
                            .then(data => {
                                if (data.code === 200) {
                                    layer.msg('删除成功', { icon: 1 });
                                    setTimeout(() => {
                                        location.reload();
                                    }, 1000);
                                } else {
                                    layer.msg(data.msg || '删除失败', { icon: 2 });
                                }
                            })
                            .catch(error => {
                                console.error('删除工艺路线失败:', error);
                                layer.msg('删除失败，请稍后重试', { icon: 2 });
                            });

                        layer.close(index);
                    });
                })
                .catch(error => {
                    console.error('检查工序数据失败:', error);
                    layer.msg('检查工序数据失败，请稍后重试', { icon: 2 });
                });
        }

        // 导出工艺路线
        function exportRoutes() {
            layer.confirm('确定要导出所有工艺路线数据吗？', {
                icon: 3,
                title: '确认导出'
            }, function (index) {
                // 显示导出进度
                const loadIndex = layer.load(1, {
                    shade: [0.3, '#fff']
                });

                fetch(`@ViewBag.WriteApiUrl/Route/export`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        operateBy: 'current_user' // 这里应该替换为当前登录用户
                    })
                })
                    .then(response => {
                        if (response.ok) {
                            return response.blob();
                        }
                        throw new Error('导出失败');
                    })
                    .then(blob => {
                        // 创建下载链接
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.style.display = 'none';
                        a.href = url;
                        a.download = `工艺路线导出_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.xlsx`;
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(a);

                        layer.close(loadIndex);
                        layer.msg('导出成功', { icon: 1 });
                    })
                    .catch(error => {
                        console.error('导出失败:', error);
                        layer.close(loadIndex);
                        layer.msg('导出失败，请稍后重试', { icon: 2 });
                    });

                layer.close(index);
            });
        }

        // 导入工艺路线
        function importRoutes() {
            layer.open({
                type: 1,
                title: '导入工艺路线',
                area: ['500px', '300px'],
                content: `
                                        <div style="padding: 20px;">
                                            <form id="importForm" enctype="multipart/form-data">
                                                <div style="margin-bottom: 15px;">
                                                    <label style="display: block; margin-bottom: 5px; font-weight: bold;">选择Excel文件：</label>
                                                    <input type="file" id="importFile" name="file" accept=".xlsx,.xls" 
                                                           style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                                                    <small style="color: #666; margin-top: 5px; display: block;">
                                                        支持.xlsx和.xls格式文件
                                                    </small>
                                                </div>
                                                <div style="text-align: right; margin-top: 20px;">
                                                    <button type="button" onclick="layer.closeAll()" 
                                                            style="padding: 8px 20px; margin-right: 10px; border: 1px solid #ddd; background: #fff; border-radius: 4px;">
                                                        取消
                                                    </button>
                                                    <button type="button" onclick="submitImport()" 
                                                            style="padding: 8px 20px; background: #007bff; color: white; border: none; border-radius: 4px;">
                                                        导入
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    `
            });
        }

        // 提交导入
        function submitImport() {
            const fileInput = document.getElementById('importFile');
            const file = fileInput.files[0];

            if (!file) {
                layer.msg('请选择要导入的文件', { icon: 0 });
                return;
            }

            const formData = new FormData();
            formData.append('file', file);
            formData.append('operateBy', 'current_user'); // 这里应该替换为当前登录用户

            const loadIndex = layer.load(1, {
                shade: [0.3, '#fff']
            });

            fetch(`@ViewBag.WriteApiUrl/Route/import`, {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    layer.close(loadIndex);

                    if (data.code === 200) {
                        layer.closeAll();
                        layer.msg('导入成功', { icon: 1 });
                        setTimeout(() => {
                            location.reload();
                        }, 1000);
                    } else {
                        layer.msg(data.msg || '导入失败', { icon: 2 });
                    }
                })
                .catch(error => {
                    console.error('导入失败:', error);
                    layer.close(loadIndex);
                    layer.msg('导入失败，请稍后重试', { icon: 2 });
                });
        }

        // 获取工艺路线表单HTML
        function getRouteFormHtml() {
            return `
                                    <div style="padding: 20px; max-height: 500px; overflow-y: auto;">
                                        <form id="routeModalForm">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="modalRouteCode">工艺路线编号 <span style="color: red;">*</span></label>
                                                        <input type="text" class="form-control" id="modalRouteCode" required>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="modalRouteName">工艺路线名称 <span style="color: red;">*</span></label>
                                                        <input type="text" class="form-control" id="modalRouteName" required>
                                                    </div>
                                                </div>
                                            </div>
                        
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="modalEnableApproval">开启审批</label>
                                                        <select class="form-control" id="modalEnableApproval">
                                                            <option value="false">否</option>
                                                            <option value="true">是</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="modalRemark">备注</label>
                                                        <input type="text" class="form-control" id="modalRemark">
                                                    </div>
                                                </div>
                                            </div>

                                            <div style="margin: 20px 0;">
                                                <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 15px;">
                                                    <h6 style="margin: 0; font-weight: 600;"><i class="fas fa-cogs"></i> 工序信息</h6>
                                                    <button type="button" class="btn btn-sm btn-success" onclick="addModalStep()">
                                                        <i class="fas fa-plus"></i> 添加工序
                                                    </button>
                                                </div>
                                                <div id="modalStepsContainer" style="background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 4px; padding: 15px; min-height: 150px;">
                                                    <div class="text-center text-muted" id="modalNoStepsMessage">
                                                        <i class="fas fa-info-circle"></i>
                                                        点击"添加工序"按钮添加工序信息
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="text-center" style="margin-top: 20px;">
                                                <button type="button" class="btn btn-secondary" onclick="layer.closeAll()">
                                                    <i class="fas fa-times"></i> 取消
                                                </button>
                                                <button type="submit" class="btn btn-primary" style="margin-left: 10px;">
                                                    <i class="fas fa-save"></i> 保存
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                `;
        }

        // 初始化工艺路线表单
        function initRouteForm(mode, data, layerIndex) {
            let modalStepIndex = 0;

            // 如果是编辑模式，填充数据
            if (mode === 'edit' && data) {
                $('#modalRouteCode').val(data.code || '');
                $('#modalRouteName').val(data.name || '');
                $('#modalEnableApproval').val(data.enableApproval ? 'true' : 'false');
                $('#modalRemark').val(data.remark || '');

                // 填充工序数据
                if (data.steps && data.steps.length > 0) {
                    $('#modalNoStepsMessage').hide();
                    data.steps.forEach(step => {
                        modalStepIndex++;
                        const stepHtml = createModalStepHtml(modalStepIndex, step);
                        $('#modalStepsContainer').append(stepHtml);
                    });
                }
            }

            // 添加工序函数
            window.addModalStep = function () {
                modalStepIndex++;
                const stepHtml = createModalStepHtml(modalStepIndex);
                $('#modalNoStepsMessage').hide();
                $('#modalStepsContainer').append(stepHtml);
            };

            // 删除工序函数
            window.removeModalStep = function (index) {
                $(`.modal-step-item[data-index="${index}"]`).remove();
                if ($('.modal-step-item').length === 0) {
                    $('#modalNoStepsMessage').show();
                }
            };

            // 表单提交处理
            $('#routeModalForm').off('submit').on('submit', function (e) {
                e.preventDefault();

                const formData = {
                    code: $('#modalRouteCode').val(),
                    name: $('#modalRouteName').val(),
                    enableApproval: $('#modalEnableApproval').val() === 'true',
                    remark: $('#modalRemark').val(),
                    operateBy: 'current_user', // 这里应该替换为当前登录用户
                    steps: []
                };

                // 编辑模式需要添加ID
                if (mode === 'edit' && data) {
                    formData.id = data.id;
                }

                // 收集工序数据
                $('.modal-step-item').each(function () {
                    const stepId = parseInt($(this).attr('data-step-id')) || 0;
                    const step = {
                        id: stepId, // JavaScript中的number可以处理long范围的整数
                        processCode: $(this).find('.step-process-code').val(),
                        processName: $(this).find('.step-process-name').val(),
                        ratio: parseFloat($(this).find('.step-ratio').val()) || null,
                        reportingPermissions: $(this).find('.step-reporting-permissions').val() || null,
                        defectiveItemList: $(this).find('.step-defective-items').val() || null,
                        testField1: $(this).find('.step-test-field1').val() || null,
                        testField2: $(this).find('.step-test-field2').val() || null
                    };

                    if (step.processCode && step.processName) {
                        formData.steps.push(step);
                    }
                });

                // 提交数据
                const url = mode === 'edit' ? '@ViewBag.WriteApiUrl/Route/save' : '@ViewBag.WriteApiUrl/Route/save';

                $.ajax({
                    url: url,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function (response) {
                        if (response.code === 200) {
                            layer.msg('保存成功', { icon: 1 });
                            setTimeout(() => {
                                layer.close(layerIndex);
                                location.reload();
                            }, 1000);
                        } else {
                            layer.msg(response.msg || '保存失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('保存失败:', error);
                        layer.msg('保存失败，请稍后重试', { icon: 2 });
                    }
                });
            });
        }

        // 创建工序HTML
        function createModalStepHtml(index, stepData) {
            const data = stepData || {};
            return `
                                    <div class="modal-step-item" data-index="${index}" data-step-id="${data.id || 0}" style="border: 1px solid #ddd; border-radius: 4px; padding: 15px; margin-bottom: 15px; background: white;">
                                        <div class="row">
                                            <div class="col-md-3">
                                                <div class="form-group" style="margin-bottom: 10px;">
                                                    <label style="font-size: 12px;">工序编号 <span style="color: red;">*</span></label>
                                                    <input type="text" class="form-control form-control-sm step-process-code" value="${data.processCode || ''}" required>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group" style="margin-bottom: 10px;">
                                                    <label style="font-size: 12px;">工序名称 <span style="color: red;">*</span></label>
                                                    <input type="text" class="form-control form-control-sm step-process-name" value="${data.processName || ''}" required>
                                                </div>
                                            </div>
                                            <div class="col-md-2">
                                                <div class="form-group" style="margin-bottom: 10px;">
                                                    <label style="font-size: 12px;">顺序号</label>
                                                    <input type="number" class="form-control form-control-sm step-sequence" value="${data.sequence || index}">
                                                </div>
                                            </div>
                                            <div class="col-md-2">
                                                <div class="form-group" style="margin-bottom: 10px;">
                                                    <label style="font-size: 12px;">报工配比</label>
                                                    <input type="number" step="0.01" class="form-control form-control-sm step-ratio" value="${data.ratio || ''}">
                                                </div>
                                            </div>
                                            <div class="col-md-2">
                                                <div class="form-group" style="margin-bottom: 10px;">
                                                    <label style="font-size: 12px;">操作</label>
                                                    <div>
                                                        <button type="button" class="btn btn-sm btn-danger" onclick="removeModalStep(${index})">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group" style="margin-bottom: 10px;">
                                                    <label style="font-size: 12px;">报工权限</label>
                                                    <input type="text" class="form-control form-control-sm step-reporting-permissions" value="${data.reportingPermissions || ''}" placeholder="逗号分隔的角色">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group" style="margin-bottom: 10px;">
                                                    <label style="font-size: 12px;">不良品项列表</label>
                                                    <input type="text" class="form-control form-control-sm step-defective-items" value="${data.defectiveItemList || ''}" placeholder="管道分隔的ID\\描述">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group" style="margin-bottom: 0;">
                                                    <label style="font-size: 12px;">测试字段1</label>
                                                    <input type="text" class="form-control form-control-sm step-test-field1" value="${data.testField1 || ''}">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group" style="margin-bottom: 0;">
                                                    <label style="font-size: 12px;">测试字段2</label>
                                                    <input type="text" class="form-control form-control-sm step-test-field2" value="${data.testField2 || ''}">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                `;
        }
    </script>
}
